/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.NonexistentEntityException;
import entities.UserStats;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.User;

/**
 *
 * @author santiagobaldrich
 */
public class UserStatsJpaController {

    public UserStatsJpaController()
    {
        emf = Persistence.createEntityManagerFactory("UNOJModelPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(UserStats userStats)
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            User user = userStats.getUser();
            if (user != null)
            {
                user = em.getReference(user.getClass(), user.getIdUser());
                userStats.setUser(user);
            }
            em.persist(userStats);
            if (user != null)
            {
                user.getUserStatsCollection().add(userStats);
                user = em.merge(user);
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(UserStats userStats) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            UserStats persistentUserStats = em.find(UserStats.class, userStats.getIdUserStats());
            User userOld = persistentUserStats.getUser();
            User userNew = userStats.getUser();
            if (userNew != null)
            {
                userNew = em.getReference(userNew.getClass(), userNew.getIdUser());
                userStats.setUser(userNew);
            }
            userStats = em.merge(userStats);
            if (userOld != null && !userOld.equals(userNew))
            {
                userOld.getUserStatsCollection().remove(userStats);
                userOld = em.merge(userOld);
            }
            if (userNew != null && !userNew.equals(userOld))
            {
                userNew.getUserStatsCollection().add(userStats);
                userNew = em.merge(userNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = userStats.getIdUserStats();
                if (findUserStats(id) == null)
                {
                    throw new NonexistentEntityException("The userStats with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            UserStats userStats;
            try
            {
                userStats = em.getReference(UserStats.class, id);
                userStats.getIdUserStats();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The userStats with id " + id + " no longer exists.", enfe);
            }
            User user = userStats.getUser();
            if (user != null)
            {
                user.getUserStatsCollection().remove(userStats);
                user = em.merge(user);
            }
            em.remove(userStats);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<UserStats> findUserStatsEntities()
    {
        return findUserStatsEntities(true, -1, -1);
    }

    public List<UserStats> findUserStatsEntities(int maxResults, int firstResult)
    {
        return findUserStatsEntities(false, maxResults, firstResult);
    }

    private List<UserStats> findUserStatsEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(UserStats.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public UserStats findUserStats(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(UserStats.class, id);
        } finally
        {
            em.close();
        }
    }

    public int getUserStatsCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<UserStats> rt = cq.from(UserStats.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

    public UserStats findByUser(User u)
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            Query q = em.createQuery("Select us from UserStats us where us.user= :user");
            q.setParameter("user", u);
            return (UserStats)q.getSingleResult();
        }
        catch (Exception e)
        {
            System.out.println("Exception: " + e.getMessage());
            return null;
        }
    }

}
